import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import NewsDetailsPage from '../components/pages/NewsDetailsPage.vue'; // 新的新闻详情组件
import HomePage from "../components/pages/HomePage.vue";
import MainLayout from "../components/layouts/MainLayout.vue";
import ContentPage from "../components/pages/ContentPage.vue";
import SearchResultsPage from "../components/pages/SearchResultsPage.vue";
import NewsListPage from "../components/pages/NewsListPage.vue"; // 新的新闻列表页组件

// 二级页面组件
import SchoolIntroduction from "../components/secondary-pages/SchoolIntroduction.vue";
import SchoolHonors from "../components/secondary-pages/SchoolHonors.vue";
import OrganizationStructure from "../components/secondary-pages/OrganizationStructure.vue";
import SignificantAchievements from "../components/secondary-pages/SignificantAchievements.vue";
import CurrentLeadership from "../components/secondary-pages/CurrentLeadership.vue";
import FormerLeadership from "../components/secondary-pages/FormerLeadership.vue";
import SchoolChronicle from "../components/secondary-pages/SchoolChronicle.vue";

// 管理页面组件
import AdminLogin from "../components/admin/AdminLogin.vue";
import AdminLayout from "../components/admin/AdminLayout.vue";
import AdminDashboard from "../components/admin/AdminDashboard.vue";
import ArticleEditor from "../components/admin/ArticleEditor.vue";
import ArticleList from "../components/admin/ArticleList.vue";

// 错误页面组件
import FailedToFetch from "../components/errors/FailedToFetch.vue";

const routes = [
    {
        path: '/',
        component: MainLayout,
        children: [
            {
                path: '',
                name: 'HomePage',
                component: HomePage,
            },
            {
                path: 'news',
                name: 'NewsList',
                component: NewsListPage
            },
            {
                path: 'news/:newsId',
                name: 'NewsDetail',
                component: NewsDetailsPage,
                props: true
            },
            {
                path: 'content',
                name: 'ContentPage',
                component: ContentPage,
            },
            {
                path: 'search',
                name: 'SearchResults',
                component: SearchResultsPage,
            },
            {
                path: 'section/:section',
                name: 'ArticleSection',
                component: SearchResultsPage,
                props: true
            },
            {
                path: 'page-manager',
                name: 'PageManager',
                component: ContentPage, // 暂时使用ContentPage，可以后续替换为专门的页面管理组件
            },
            {
                path: 'school/introduction',
                name: 'SchoolIntroduction',
                component: SchoolIntroduction,
            },
            {
                path: 'school/honors',
                name: 'SchoolHonors',
                component: SchoolHonors,
            },
            {
                path: 'school/organization',
                name: 'OrganizationStructure',
                component: OrganizationStructure,
            },
            {
                path: 'school/achievements',
                name: 'SignificantAchievements',
                component: SignificantAchievements,
            },
            {
                path: 'school/current-leadership',
                name: 'CurrentLeadership',
                component: CurrentLeadership,
            },
            {
                path: 'school/former-leadership',
                name: 'FormerLeadership',
                component: FormerLeadership,
            },
            {
                path: 'school/chronicle',
                name: 'SchoolChronicle',
                component: SchoolChronicle,
            }
        ]
    },
    // 用户登录路由
    {
        path: '/login',
        name: 'Login',
        component: AdminLogin
    },
    // 管理员登录路由（重定向到通用登录页）
    {
        path: '/admin/login',
        redirect: { name: 'Login', query: { redirect: '/admin' } }
    },
    {
        path: '/admin',
        component: AdminLayout,
        children: [
            {
                path: '',
                name: 'AdminDashboard',
                component: AdminDashboard,
                meta: { requiresAuth: true }
            },
            {
                path: 'articles',
                name: 'ArticleList',
                component: ArticleList,
                meta: { requiresAuth: true }
            },
            {
                path: 'articles/edit/:id',
                name: 'ArticleEdit',
                component: ArticleEditor,
                props: true,
                meta: { requiresAuth: true }
            },
            {
                path: 'articles/new',
                name: 'ArticleCreate',
                component: ArticleEditor,
                meta: { requiresAuth: true }
            },
            {
                path: 'articles/create',
                redirect: { name: 'ArticleCreate' },
                meta: { requiresAuth: true }
            }
        ]
    },
    // 404 页面 - 捕获所有未匹配的路由
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: FailedToFetch
    }
];

const router = createRouter({
    // 使用Hash模式避免服务器配置问题，解决直接访问URL和刷新页面404的问题
    // history: createWebHistory(), // History模式需要服务器配置
    history: createWebHashHistory(), // Hash模式，无需服务器配置，URL格式：/#/news/97686
    routes,
});

import request from '../utils/request';
import eventBus from '../utils/eventBus';

// 路由导航守卫，实现权限控制和重定向处理
router.beforeEach(async (to, from, next) => {
    // 检查是否是404页面且需要重定向
    if (to.name === 'NotFound' && to.params.pathMatch) {
        const originalPath = '/' + to.params.pathMatch.join('/');
        console.log('路由守卫检测到404，原始路径:', originalPath);

        // 如果是有效的路由路径，尝试重定向
        if (originalPath.startsWith('/news/') ||
            originalPath.startsWith('/admin/') ||
            originalPath.startsWith('/search') ||
            originalPath.startsWith('/section/')) {
            console.log('重定向到Hash模式:', originalPath);
            window.location.replace(window.location.origin + '/#' + originalPath);
            return;
        }
    }

    // 检查路由是否需要登录
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // 检查用户是否已登录
        const token = localStorage.getItem('admin_token');
        if (!token) {
            // 未登录，跳转到登录页面
            next({ name: 'Login', query: { redirect: to.fullPath } });
            return;
        }

        try {
            // 使用axios发送权限验证请求
            const result = await request.get('/api/user/permission');

            if (result.code === 200) {
                // 检查用户是否有有效的管理权限
                const permissions = result.data.permissions || [];

                // 检查是否只有"学生"或"教师"权限
                const onlyHasStudentOrTeacherPermission = permissions.length > 0 &&
                    permissions.every(perm => perm === "学生" || perm === "教师");

                if (permissions.length > 0 && !onlyHasStudentOrTeacherPermission) {
                    // 用户有有效的管理权限，允许访问
                    next();
                } else {
                    // 用户没有有效的管理权限，跳转到登录页面
                    let errorMsg = '权限验证失败：';
                    if (permissions.length === 0) {
                        errorMsg += '用户没有任何系统权限';
                    } else {
                        errorMsg += '用户只有学生或教师权限，无法访问管理面板';
                    }
                    console.error(errorMsg);
                    localStorage.removeItem('admin_token');
                    localStorage.removeItem('admin_user');
                    // 触发登出事件，通知Header组件更新状态
                    eventBus.emit('user-logout');
                    next({ name: 'Login', query: { redirect: to.fullPath } });
                }
            } else {
                // API请求失败，跳转到登录页面
                console.error('权限验证失败：', result.msg || '权限验证请求失败');
                localStorage.removeItem('admin_token');
                localStorage.removeItem('admin_user');
                // 触发登出事件，通知Header组件更新状态
                eventBus.emit('user-logout');
                next({ name: 'Login', query: { redirect: to.fullPath } });
            }
        } catch (error) {
            console.error('权限验证请求失败:', error);
            // 发生错误，跳转到登录页面
            localStorage.removeItem('admin_token');
            localStorage.removeItem('admin_user');
            // 触发登出事件，通知Header组件更新状态
            eventBus.emit('user-logout');
            next({ name: 'Login', query: { redirect: to.fullPath } });
        }
    } else {
        // 不需要登录，直接放行
        next();
    }
});

export default router;